package com.aviccxzx.smarthome.fragment;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.aviccxzx.smarthome.ConfigModule.DoorAirlinkCountdownActivity;
import com.aviccxzx.smarthome.ConfigModule.GosAirlinkChooseDeviceWorkWiFiActivity;
import com.aviccxzx.smarthome.DeviceModule.GosMessageHandler;
import com.aviccxzx.smarthome.MsgID;
import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.UserModule.AddDevSuccActivity;
import com.aviccxzx.smarthome.UserModule.AddFailActivity;
import com.aviccxzx.smarthome.UserModule.AlarmActivity;
import com.aviccxzx.smarthome.UserModule.DoorLockActivity;
import com.aviccxzx.smarthome.UserModule.GasActivity;
import com.aviccxzx.smarthome.UserModule.GatewaySetActivity;
import com.aviccxzx.smarthome.UserModule.MessageCenterActivity;
import com.aviccxzx.smarthome.UserModule.NewSceneAct;
import com.aviccxzx.smarthome.UserModule.SmokeActivity;
import com.aviccxzx.smarthome.UserModule.WaterActivity;
import com.aviccxzx.smarthome.entity.BindSucBean;
import com.aviccxzx.smarthome.entity.DeviceWorkBean;
import com.aviccxzx.smarthome.entity.FeedBack;
import com.aviccxzx.smarthome.netutil.app.App;
import com.aviccxzx.smarthome.netutil.msg.MsgCenter;
import com.aviccxzx.smarthome.netutil.msg.MsgListener;
import com.aviccxzx.smarthome.service.RetrofitHelper;
import com.aviccxzx.smarthome.service.RetrofitService;
import com.aviccxzx.smarthome.utils.DialogUtil;
import com.aviccxzx.smarthome.utils.PermissionTool;
import com.aviccxzx.smarthome.utils.ToastUtil;
import com.aviccxzx.smarthome.view.ListViewAdaptWidth;
import com.gizwits.gizwifisdk.api.GizDeviceSharing;
import com.gizwits.gizwifisdk.api.GizWifiCentralControlDevice;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.api.GizWifiSDK;
import com.gizwits.gizwifisdk.enumration.GizDeviceSharingUserRole;
import com.gizwits.gizwifisdk.enumration.GizDeviceSharingWay;
import com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus;
import com.gizwits.gizwifisdk.enumration.GizWifiDeviceType;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.gizwits.gizwifisdk.listener.GizDeviceSharingListener;
import com.gizwits.gizwifisdk.listener.GizWifiCentralControlDeviceListener;
import com.gizwits.gizwifisdk.listener.GizWifiDeviceListener;
import com.gizwits.gizwifisdk.listener.GizWifiSDKListener;
import com.google.gson.Gson;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import cn.jpush.android.api.JPushInterface;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import zxing.CaptureActivity;

import static com.aviccxzx.smarthome.DeviceModule.GosDeviceModuleBaseActivity.deviceslist;
import static com.aviccxzx.smarthome.UserModule.AddDevSuccActivity.addDevSuccInstance;
import static com.aviccxzx.smarthome.UserModule.AddFailActivity.addDeviFailInstance;
import static com.aviccxzx.smarthome.fragment.CamFragment.cams;
import static com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus.GizDeviceOffline;
import static com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus.GizDeviceOnline;


/**
 * Created by joey on 2016/11/8.
 */
public class DeviceListFragment extends Fragment implements EasyPermissions.PermissionCallbacks {
    ImageView add_img, msgcenter_img, gateway_img;
    List<String> listmenu;
    private PopupWindow popupWindow;
    private ArrayAdapter<String> adapter;
    private Window window;
    LinearLayout add_twobar_ll, gateway_property_ll, onekey_switch;
    ListView device_list;
    TextView add_gateway_text, add_device_text, battery_tv, zigbee_state_tv, wifistate_tv;
    /**
     * 与APP绑定的设备的ProductKey
     */
    String softssid, uid, token;
    /**
     * 存储器
     */
    public SharedPreferences spf;
    /**
     * 存储器默认名称
     */
    public static final String SPF_Name = "set";

    /**
     * 扫描跳转Activity RequestCode
     */
    public int REQUEST_CODE = 111;

    public DeviceListFragment() {
    }

    public static Boolean hasGateWay = false;
    public static List<GizWifiDevice> subList = new ArrayList<>();
    String gatewayname = "";
    public static GizWifiCentralControlDevice mDevice = null;
    public static GizWifiCentralControlDevice mGprsDevice = null;
    DeviceListAdapter deviceListadapter = null;
    int getcolor = 0;
    List<String> pks;
    public static List<GizWifiDevice> myDeviceList = new ArrayList<>();
    public static String device_macs = "";//所有子设备的mac
    TextView onekey_open;
    TextView onekey_close;
    Set<String> alarmSet;
    Set<String> newSmoke;
    Set<String> oldSmoke;
    public static boolean isFromDeviceList = false;//解决设备删除时偶尔弹出“管理员已绑定界面的问题”，只在添加设备过程中需要弹出该界面处放行，删除设备处卡住即可。

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.devicelist_fragment_fragment, container, false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            view = inflater.inflate(R.layout.devicelist_fragment_fragment_v19, container, false);
        }
        return view;

    }

    private ProgressDialog progressDialog;

    public void showProgressDialog(String msg) {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
        progressDialog = new ProgressDialog(getActivity(), ProgressDialog.THEME_DEVICE_DEFAULT_LIGHT);
        progressDialog.setMessage(msg);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(true);
        try {
            progressDialog.show();
        } catch (WindowManager.BadTokenException exception) {
            exception.printStackTrace();
        }
    }

    /**
     * 取消对话框显示
     */
    public void disMissDialog() {
        try {
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
                progressDialog = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        pks = new ArrayList<>();
        pks.add(MsgID.PK_GATE);
        pks.add(MsgID.PK_WATER);
        pks.add(MsgID.PK_ALARM);
        pks.add(MsgID.PK_GAS);
        pks.add(MsgID.PK_SMOKE);
        pks.add(MsgID.PK_DOOR);

        GizWifiSDK.sharedInstance().getBoundDevices(uid, token, pks);
        GizWifiSDK.sharedInstance().setListener(mListener);

    }

    public static Boolean isSubed = false; //为了解决退出帐号时解除订阅时的回调问题
    /**
     * 实现回调
     */
    GizWifiSDKListener mListener = new GizWifiSDKListener() {
        @Override
        public void didDiscovered(GizWifiErrorCode result, List<GizWifiDevice> deviceList) {
            super.didDiscovered(result, deviceList);
            deviceslist = deviceList;
            mDevice = null;
            mGprsDevice = null;
            for (int i = 0; i < deviceList.size(); i++) {
                if (deviceList.get(i).getProductKey().equals(MsgID.PK_GATE) && deviceList.get(i).isBind() && deviceList.get(i).getMacAddress().length() == 12) {
                    mDevice = (GizWifiCentralControlDevice) deviceList.get(i);
                    if (mDevice != null) {
                        spf.edit().putString("wifidid", mDevice.getDid()).commit();
                    }
                    break;
                }
            }
            for (int i = 0; i < deviceList.size(); i++) {
                if (deviceList.get(i).getProductKey().equals(MsgID.PK_GATE) && deviceList.get(i).isBind() && deviceList.get(i).getMacAddress().length() == 15) {
                    mGprsDevice = (GizWifiCentralControlDevice) deviceList.get(i);
                    break;
                }
            }
            //解决双网关解绑时GPRS版本解绑失败的问题
            if (mDevice == null && mGprsDevice != null) {
                //            if(mGprsDevice!=null&&mGprsDevice.getNetStatus()==GizDeviceOffline){
                //如果只有GPRS网关是绑定状态，说明之前解绑时GPRS网关解绑失败 需要再次解绑
                GizWifiSDK.sharedInstance().unbindDevice(uid, token, mGprsDevice.getDid());
            }
            if (mDevice != null && mDevice.getNetStatus() == GizDeviceOffline && (mGprsDevice != null && mGprsDevice.getNetStatus() != GizDeviceOffline)) {
                mDevice = mGprsDevice;
                mDevice.setListener(controlListener);
                mDevice.setSubscribe(MsgID.PS, true);
            }

            if (mDevice != null) {
                if (mDevice.isBind() && !mDevice.isSubscribed() && !isSubed) {
                    mDevice.setListener(controlListener);
                    mDevice.setSubscribe(MsgID.PS, true);
                }

                /*subList = mDevice.getSubDeviceList();
                String addmac = spf.getString("addMac", "");
                if (TextUtils.isEmpty(addmac)) {
                    for (int i = 0; i < subList.size(); i++) {
                        if (!subList.get(i).isBind()) {
                            //网关下的子设备如果是没有绑定的 就再次删除
                            mDevice.deleteSubDevice(subList.get(i));
                        }
                    }
                }
                for (int i = 0; i < subList.size(); i++) {
                    if (!subList.get(i).isBind()) {
                        subList.remove(i);
                    }
                }*/
                subList.clear();
                myDeviceList.clear();
                for (int j = 0; j < deviceList.size(); j++) {
                    //                    if (subList.size() == 0) {
                    if (deviceList.get(j).getSharingRole().equals(GizDeviceSharingUserRole.GizDeviceSharingOwner) && deviceList.get(j).getProductType().equals(GizWifiDeviceType.GizDeviceSub) &&
                            !TextUtils.isEmpty(deviceList.get(j).getDid()) && deviceList.get(j).isBind() && !subList.contains(deviceList.get(j))) {
                        subList.add(deviceList.get(j));
                    }
                    //                    }
                    if (deviceList.get(j).getSharingRole() != null && deviceList.get(j).getSharingRole().equals(GizDeviceSharingUserRole.GizDeviceSharingGuest)
                            && deviceList.get(j).getProductType().equals(GizWifiDeviceType.GizDeviceSub) && !myDeviceList.contains(deviceList.get(j))) {
                        //子设备
                        myDeviceList.add(deviceList.get(j));
                    }
                }
                subList.removeAll(myDeviceList);
                subList.addAll(myDeviceList);
                Message message = new Message();
                message.what = 100;
                handler.sendMessage(message);
                disMissDialog();
                hasGateWay = true;
            } else {
                if (myDeviceList.size() > 0) {
                    Message message = new Message();
                    message.what = 104;
                    handler.sendMessage(message);
                    disMissDialog();
                } else {
                    hasGateWay = false;
                    Message message = new Message();
                    message.what = 103;
                    handler.sendMessage(message);
                    disMissDialog();
                }
            }
        }

        @Override
        public void didUnbindDevice(GizWifiErrorCode result, String did) {
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS && isFromDeviceList) {
                // 解绑成功
                Message message = new Message();
                message.what = 105;

                handler.sendMessage(message);
            } else {
            }
        }

        @Override
        public void didBindDevice(GizWifiErrorCode result, String did) {
            if (addedDevice == null) {
                return;
            }
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                //绑定成功 分享
                //强行分享 使其成为管理员、
                // 设置设备分享监听
                bindTimer = new Timer();
                bindTimer.schedule(new TimerTask() {
                    int i = 35;

                    @Override
                    public void run() {
                        i--;
                        if (i == 0) {
                            Looper.prepare();
                            Message message = new Message();
                            message.what = 102;
                            handler.sendMessage(message);
                            Looper.loop();
                        } else if (!TextUtils.isEmpty(addedDevice.getDid())) {
                            Looper.prepare();
                            GizDeviceSharing.setListener(setRoleListener);
                            // 在设备列表中找到可以分享的设备
                            // 二维码分享设备
                            GizDeviceSharing.sharingDevice(token, addedDevice.getDid(), GizDeviceSharingWay.GizDeviceSharingByQRCode, null, null);
                            Log.i("addlogg", "setRoleListener===绑定成功后开始分享" + setRoleListener.toString() + "....." + new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date(System.currentTimeMillis())));
                            Looper.loop();
                        }
                    }
                }, 0, 1000);
            } else if (result == GizWifiErrorCode.GIZ_OPENAPI_ONLY_OWNER_CAN_BIND) {
                //打上标记 可以提示管理员已绑定界面的标记
                isFromDeviceList = true;
                Message message = new Message();
                message.what = 105;
                handler.sendMessage(message);
            } else {
                // 绑定失败 提示添加设备失败
                Message message = new Message();
                message.what = 102;
                handler.sendMessage(message);
            }
        }
    };

    Boolean powersupply;
    int battery;
    Boolean zig, wifistate;
    byte[] MAC_Address;
    byte[] ICCID;
    byte[] Imei;
    /**
     * 获取上报的设备信息
     */
    private final GizWifiDeviceListener controlListener = new GizWifiDeviceListener() {
        @Override
        public void didReceiveData(GizWifiErrorCode result, GizWifiDevice device, ConcurrentHashMap<String, Object> dataMap, int sn) {
            super.didReceiveData(result, device, dataMap, sn);
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                if (dataMap.get("data") != null) {
                    ConcurrentHashMap<String, Object> map = (ConcurrentHashMap<String, Object>) dataMap.get("data");
                    if (map != null && map.size() > 0) {
                        if (map.get("PowerSupplyMode") != null) {
                            powersupply = (Boolean) map.get("PowerSupplyMode");
                        }
                        if (powersupply) {
                            battery_tv.setText("插电");
                        } else {
                            if (map.get("Battery") != null) {
                                battery = (int) map.get("Battery");
                            }
                            spf.edit().putString("Battery", battery + "").commit();
                            battery_tv.setText(battery + "%");
                        }
                        if (map.get("Zigbee_State") != null) {
                            zig = (Boolean) map.get("Zigbee_State");
                        }
                        if (map.get("WiFi_State") != null) {
                            wifistate = (Boolean) map.get("WiFi_State");
                        }
                        if (zig) {
                            zigbee_state_tv.setText("正常");
                        } else {
                            zigbee_state_tv.setText("断开");
                        }
                        if (wifistate) {
                            wifistate_tv.setText("正常");
                        } else {
                            wifistate_tv.setText("断开");
                        }
                        spf.edit().putString("wifistate", wifistate_tv.getText().toString()).commit();
                        spf.edit().putString("zigbeestate", zigbee_state_tv.getText().toString()).commit();
                        if (map.get("MAC_Address") != null) {
                            MAC_Address = (byte[]) map.get("MAC_Address");
                        }
                        if (map.get("ICCID") != null) {
                            ICCID = (byte[]) map.get("ICCID");
                        }
                        if (map.get("IMEI") != null) {
                            Imei = (byte[]) map.get("IMEI");
                        }
                        String GprsImei = "";
                        if (Imei != null) {
                            //双网版本
                            GprsImei = bytesToHex(Imei).toString().replace(" ", "");
                            char[] chars = GprsImei.toCharArray();
                            StringBuffer sb = new StringBuffer();
                            for (int i = 1; i < chars.length; i += 2) {
                                sb.append(chars[i]);
                            }
                            GprsImei = sb.toString();
                            String patte = "^(0)\\d{14}$";
                            if (GprsImei.matches(patte)) {
                                //单WIFI时 传空的IMEI
                                bindGprs("");
                            } else {
                                bindGprs(GprsImei);
                            }
                        }
                        if (map.get("Red") != null && map.get("Green") != null && map.get("Blue") != null) {
                            int Red = (int) map.get("Red");
                            int Green = (int) map.get("Green");
                            int Blue = (int) map.get("Blue");
                            getcolor = Color.argb(255, Red, Green, Blue);
                        }
                    }
                }
            }
        }
    };

    private void bindGprs(final String GprsImei) {
        String uid = spf.getString("Uid", "");
        String Mac = spf.getString("gatemac", "");
        RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
        Gson gson = new Gson();
        HashMap<String, String> paramsMap = new HashMap<>();

        /*{
                "imei": "string",
                "mac": "string",
                "product_key": "string",
                "product_secret": "string",
                "uid": "string"
        }*/
        //        paramsMap.put("imei", "");
        paramsMap.put("imei", GprsImei);
        paramsMap.put("mac", Mac);
        paramsMap.put("product_key", MsgID.PK_GATE);
        paramsMap.put("product_secret", MsgID.PS);
        paramsMap.put("uid", uid);

        String strEntity = gson.toJson(paramsMap);

        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);
        Call<BindSucBean> call = service.bindsucess(body);
        call.enqueue(new Callback<BindSucBean>() {
            @Override
            public void onResponse(Call<BindSucBean> call, Response<BindSucBean> response) {
                if (response.body() != null && response.body().getData() != null) {
                    int code = response.body().getCode();
                    if (code == 1) {
                        //成功
                        String imei = response.body().getData().getImei();
                        if (!TextUtils.isEmpty(imei)) {
                            spf.edit().putString("Imei", imei).commit();
                        }
                    } else {
                        //失败
                        new DialogUtil(getActivity(), true, true, "GPRS绑定失败，GPRS功能会失效", "舍弃GPRS", "重新绑定", new DialogUtil.SureInterfance() {
                            @Override
                            public void sureTodo() {
                                bindGprs(GprsImei);
                            }

                            @Override
                            public void cancle() {

                            }
                        }).showCustomDialog();
                    }
                }
            }

            @Override
            public void onFailure(Call<BindSucBean> call, Throwable t) {
            }
        });
    }

    /**
     * 判断整个字符串的所有字节都为“0”
     *
     * @param str
     * @return
     */
    public boolean test(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (str.substring(i, 1) != "0")
                return false;
        }
        return true;
    }

    /**
     * 没有网关时初始化回去
     */
    public void goBack() {
        initUi();
        //网关虚化
        gateway_img.setBackgroundResource(R.mipmap.gateway_pic_offline);
        //网关属性隐藏
        gateway_property_ll.setVisibility(View.GONE);
        msgcenter_img.setVisibility(View.GONE);
        add_img.setVisibility(View.GONE);

        //设置子设备列表的界面
        //        layout_swipe_refresh.setVisibility(View.GONE);
        device_list.setVisibility(View.GONE);
        onekey_switch.setVisibility(View.GONE);
        add_twobar_ll.setVisibility(View.VISIBLE);
        add_gateway_text.setVisibility(View.VISIBLE);
        add_device_text.setVisibility(View.GONE);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 100:
                    if (mDevice != null) {
                        UpdateUIgate();
                    }
                    break;
                case 103:
                    //恢复界面
                    goBack();
                    tagSet.clear();
                    if (cams.size() > 0) {
                        //有摄像头
                        for (int i = 0; i < cams.size(); i++) {
                            tagSet.add(cams.get(i).getYst());
                        }
                    }
                    tagSet.add(uid);
                    JPushInterface.setTags(getActivity(), 0, tagSet);
                    break;
                case 104:
                    //更新设备列表
                    UpdateUIdevice("share");
                    break;
                case 101:
                    if (bindTimer != null) {
                        bindTimer.cancel();
                        bindTimer = null;
                    }
                    if (timer != null) {
                        timer.cancel();
                        timer = null;
                    }
                    if (DoorAirlinkCountdownActivity.doorCountInstance != null) {
                        DoorAirlinkCountdownActivity.doorCountInstance.finish();
                    }
                    String addmac = spf.getString("addMac", "");
                    if (addDeviFailInstance == null && !TextUtils.isEmpty(addmac)) {
                        Intent succes = new Intent(getActivity(), AddDevSuccActivity.class);
                        startActivity(succes);
                    }
                    spf.edit().putString("addMac", null).commit();
                    break;
                case 102:
                    if (timer != null) {
                        timer.cancel();
                        timer = null;
                    }
                    if (bindTimer != null) {
                        bindTimer.cancel();
                        bindTimer = null;
                    }
                    if (DoorAirlinkCountdownActivity.doorCountInstance != null) {
                        DoorAirlinkCountdownActivity.doorCountInstance.finish();
                    }
                    if (addedDevice != null && !TextUtils.isEmpty(addedDevice.getDid())) {
                        mDevice.setListener(mSubdeviceListener);
                        mDevice.deleteSubDevice(addedDevice);
                    }
                    if (addDevSuccInstance == null && !TextUtils.isEmpty(spf.getString("addMac", ""))) {
                        Intent fail = new Intent(getActivity(), AddFailActivity.class);
                        startActivity(fail);
                    }
                    spf.edit().putString("addMac", null).commit();
                    break;
                case 105:
                    if (timer != null) {
                        timer.cancel();
                        timer = null;
                    }
                    if (bindTimer != null) {
                        bindTimer.cancel();
                        bindTimer = null;
                    }
                    if (addedDevice != null && !TextUtils.isEmpty(addedDevice.getDid())) {
                        mDevice.setListener(mSubdeviceListener);
                        mDevice.deleteSubDevice(addedDevice);
                        //                        GizWifiSDK.sharedInstance().unbindDevice(uid, token,
                        //                                addedDevice.getDid());
                    }
                    if (DoorAirlinkCountdownActivity.doorCountInstance != null) {
                        DoorAirlinkCountdownActivity.doorCountInstance.finish();
                    }
                    if (addDevSuccInstance == null && hasGateWay && isFromDeviceList && !TextUtils.isEmpty(spf.getString("addMac", ""))) {
                        Intent intent = new Intent(getActivity(), AddFailActivity.class);
                        intent.putExtra("bind", true);
                        startActivity(intent);
                    }
                    spf.edit().putString("addMac", null).commit();
                    break;
            }
        }
    };


    GizWifiDeviceListener mSubdeviceListener = new
            GizWifiCentralControlDeviceListener() {
                @Override
                public void didUpdateSubDevices(GizWifiCentralControlDevice device, GizWifiErrorCode result,
                                                List<GizWifiDevice> subDeviceList) {
                    if (addedDevice != null) {
                        if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS || result == GizWifiErrorCode.GIZ_SDK_SUBDEVICE_INVALID) {
                            // 删除成功
                            GizWifiSDK.sharedInstance().setListener(unbindSubListener);
                            GizWifiSDK.sharedInstance().unbindDevice(uid, token,
                                    addedDevice.getDid());
                        } else {
                            // 删除失败时再次删除
                            mDevice.setListener(mSubdeviceListener);
                            mDevice.deleteSubDevice(addedDevice);
                        }
                    }
                }
            };
    GizWifiSDKListener unbindSubListener = new GizWifiSDKListener() {
        @Override
        public void didUnbindDevice(GizWifiErrorCode result, String did) {
            super.didUnbindDevice(result, did);
            if (addedDevice != null) {
                if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                    // 解绑成功

                } else {
                    // 解绑失败
                    GizWifiSDK.sharedInstance().setListener(unbindSubListener);
                    GizWifiSDK.sharedInstance().unbindDevice(uid, token,
                            addedDevice.getDid());
                }
            }
        }
    };

    public void UpdateUIgate() {
        initUi();
        //网关显示
        //显示网关的属性信息
        //设置网关信息
        //显示消息中心和添加图标

        gateway_property_ll.setVisibility(View.VISIBLE);
        msgcenter_img.setVisibility(View.VISIBLE);
        add_img.setVisibility(View.VISIBLE);

        if (!TextUtils.isEmpty(mDevice.getRemark()) && mDevice.getRemark().equals("GPRS_网关")) {
            wifistate_tv.setText("断开");
            //WIFI版本断网时，再判断GPRS版本的网络状态
            if (mDevice.getNetStatus() != GizDeviceOffline) {
                //如果GPRS有网，WIFI版本显示断网，但图片那些状态不变
                gateway_img.setBackgroundResource(R.mipmap.gateway_pic);
            } else {
                //GPRS版本没网时，WIFI版本显示断网+图片那些状态也断网
                gateway_img.setBackgroundResource(R.mipmap.gateway_pic_offline);
            }
        } else {
            //wifi版本没有断网时用WIFI版本的
            if (mDevice.getNetStatus() == GizDeviceOffline) {
                gateway_img.setBackgroundResource(R.mipmap.gateway_pic_offline);
                wifistate_tv.setText("断开");
                zigbee_state_tv.setText("断开");
            } else {
                gateway_img.setBackgroundResource(R.mipmap.gateway_pic);
                wifistate_tv.setText("正常");
                zigbee_state_tv.setText("正常");
            }
        }
        gatewayname = mDevice.getAlias();
        String mac = mDevice.getMacAddress();
        if (!TextUtils.isEmpty(mac)) {
            spf.edit().putString("gatemac", mac).commit();
        }
        UpdateUIdevice("");
    }

    public static GizWifiDevice addedDevice = null;
    public static GizWifiDevice addDeviceSucdev = null;
    public static Set<String> tagSet = new LinkedHashSet<>();
    List<DeviceWorkBean.DataBean> deviceworkList;

    /**
     * 获取开关状态
     */
    public void getDisarmSwitch() {
        RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
        Call<DeviceWorkBean> call = service.getDisarmSwitchChildList(device_macs.substring(0, device_macs.length() - 1));
        call.enqueue(new Callback<DeviceWorkBean>() {
            @Override
            public void onResponse(Call<DeviceWorkBean> call, Response<DeviceWorkBean> response) {
                if (response != null && response.body() != null) {
                    int code = response.body().getCode();
                    if (code == 200) {
                        deviceworkList = response.body().getData();
                        deviceListadapter.setDeviceList(subList);
                    }
                }
            }

            @Override
            public void onFailure(Call<DeviceWorkBean> call, Throwable t) {

            }
        });
    }

    public void UpdateUIdevice(String tag) {
        if (tag.equals("share")) {
            subList = myDeviceList;
        }
        if (subList.size() > 0) {
            for (GizWifiDevice device : subList) {
                device.setListener(deviceListener);
                if (device.getNetStatus() == GizDeviceOnline) {
                    if (device.getProductKey().equals(MsgID.PK_DOOR)) {
                        device.setSubscribe(MsgID.PS_DOOR, true);
                    } else if (device.getProductKey().equals(MsgID.PK_WATER)) {
                        device.setSubscribe(MsgID.PS_WATER, true);
                    } else if (device.getProductKey().equals(MsgID.PK_GAS)) {
                        device.setSubscribe(MsgID.PS_GAS, true);
                    } else if (device.getProductKey().equals(MsgID.PK_SMOKE)) {
                        device.setSubscribe(MsgID.PS_SMOKE, true);
                    } else if (device.getProductKey().equals(MsgID.PK_ALARM)) {
                        device.setSubscribe(MsgID.PS_ALARM, true);
                    }
                }
            }
            //设置子设备列表的界面
            device_list.setVisibility(View.VISIBLE);
            onekey_switch.setVisibility(View.VISIBLE);
            String key = spf.getString("onekey", "");
            if (key.equals("close")) {
                onekey_open.setBackgroundResource(R.drawable.oval_shape_unselected);
                onekey_open.setTextColor(getResources().getColor(R.color.text_gray_light));
                onekey_close.setBackgroundResource(R.drawable.oval_shape_selected);
                onekey_close.setTextColor(getResources().getColor(R.color.title_common_color));
            } else {
                onekey_close.setBackgroundResource(R.drawable.oval_shape_unselected);
                onekey_close.setTextColor(getResources().getColor(R.color.text_gray_light));
                onekey_open.setBackgroundResource(R.drawable.oval_shape_selected);
                onekey_open.setTextColor(getResources().getColor(R.color.title_common_color));
            }
            device_macs = "";
            for (int i = 0; i < subList.size(); i++) {
                //极光推送标签
                device_macs = device_macs + subList.get(i).getMacAddress() + ",";
            }
            getDisarmSwitch();

            //判断极光推送是否打开
            boolean istag = spf.getBoolean("tagset", true);
            if (istag) {
                tagSet.clear();
                if (cams.size() > 0) {
                    //有摄像头
                    for (int i = 0; i < cams.size(); i++) {
                        tagSet.add(cams.get(i).getYst());
                    }
                }
                for (int i = 0; i < subList.size(); i++) {
                    //极光推送标签
                    tagSet.add(subList.get(i).getMacAddress());
                }
                if (mDevice != null) {
                    tagSet.add(mDevice.getMacAddress());
                }
                tagSet.add(uid);
                JPushInterface.setTags(getActivity(), 0, tagSet);
            }

            deviceListadapter.setDeviceList(subList);
            add_twobar_ll.setVisibility(View.GONE);

            device_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    Intent intent = null;
                    String deviceType = subList.get(i).getProductKey();
                    if (deviceType.equals(MsgID.PK_DOOR)) {
                        intent = new Intent(getActivity(), DoorLockActivity.class);
                        intent.putExtra("deviceName", !TextUtils.isEmpty(subList.get(i).getAlias()) ? subList.get(i).getAlias() : subList.get(i).getProductName());
                        intent.putExtra("deviceMac", subList.get(i).getMacAddress());
                        if (alarmSet.contains(subList.get(i).getMacAddress())) {
                            intent.putExtra("alarm", true);
                        }
                        if (subList.get(i).getNetStatus() == GizDeviceOffline) {
                            intent.putExtra("netStatus", "离线");
                        }
                        startActivity(intent);
                    } else if (deviceType.equals(MsgID.PK_WATER)) {
                        intent = new Intent(getActivity(), WaterActivity.class);
                        intent.putExtra("deviceName", !TextUtils.isEmpty(subList.get(i).getAlias()) ? subList.get(i).getAlias() : subList.get(i).getProductName());
                        intent.putExtra("deviceMac", subList.get(i).getMacAddress());
                        if (alarmSet.contains(subList.get(i).getMacAddress())) {
                            intent.putExtra("alarm", true);
                        }
                        if (subList.get(i).getNetStatus() == GizDeviceOffline) {
                            intent.putExtra("netStatus", "离线");
                        }
                        startActivity(intent);
                    } else if (deviceType.equals(MsgID.PK_GAS)) {
                        intent = new Intent(getActivity(), GasActivity.class);
                        intent.putExtra("deviceName", !TextUtils.isEmpty(subList.get(i).getAlias()) ? subList.get(i).getAlias() : subList.get(i).getProductName());
                        intent.putExtra("deviceMac", subList.get(i).getMacAddress());
                        if (alarmSet.contains(subList.get(i).getMacAddress())) {
                            intent.putExtra("alarm", true);
                        }
                        if (subList.get(i).getNetStatus() == GizDeviceOffline) {
                            intent.putExtra("netStatus", "离线");
                        }
                        startActivity(intent);
                    } else if (deviceType.equals(MsgID.PK_SMOKE)) {
                        intent = new Intent(getActivity(), SmokeActivity.class);
                        intent.putExtra("deviceName", !TextUtils.isEmpty(subList.get(i).getAlias()) ? subList.get(i).getAlias() : subList.get(i).getProductName());
                        intent.putExtra("deviceMac", subList.get(i).getMacAddress());
                        if (alarmSet.contains(subList.get(i).getMacAddress())) {
                            intent.putExtra("alarm", true);
                        }
                        if (subList.get(i).getNetStatus() == GizDeviceOffline) {
                            intent.putExtra("netStatus", "离线");
                        }
                        startActivity(intent);
                    } else if (deviceType.equals(MsgID.PK_ALARM)) {
                        intent = new Intent(getActivity(), AlarmActivity.class);
                        intent.putExtra("deviceName", !TextUtils.isEmpty(subList.get(i).getAlias()) ? subList.get(i).getAlias() : subList.get(i).getProductName());
                        intent.putExtra("deviceMac", subList.get(i).getMacAddress());
                        if (alarmSet.contains(subList.get(i).getMacAddress())) {
                            intent.putExtra("alarm", true);
                        }
                        if (subList.get(i).getNetStatus() == GizDeviceOffline) {
                            intent.putExtra("netStatus", "离线");
                        }
                        startActivity(intent);
                    }
                }
            });
        } else {
            tagSet.clear();
            if (cams.size() > 0) {
                //有摄像头
                for (int i = 0; i < cams.size(); i++) {
                    tagSet.add(cams.get(i).getYst());
                }
            }
            if (mDevice != null) {
                tagSet.add(mDevice.getMacAddress());
            }
            tagSet.add(uid);
            JPushInterface.setTags(getActivity(), 0, tagSet);
            //设置子设备列表的界面
            device_list.setVisibility(View.GONE);
            onekey_switch.setVisibility(View.GONE);
            add_twobar_ll.setVisibility(View.VISIBLE);
            if (hasGateWay) {
                add_gateway_text.setVisibility(View.GONE);
                add_device_text.setVisibility(View.VISIBLE);
            } else {
                add_gateway_text.setVisibility(View.VISIBLE);
                add_device_text.setVisibility(View.GONE);
            }
            disMissDialog();
        }

    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();

        getView().findViewById(R.id.add_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (popupWindow == null) {
                    View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popurwindow_menu, null);
                    ListViewAdaptWidth listViewAdaptWidth = (ListViewAdaptWidth) contentView.findViewById(R.id.listView);
                    adapter = new ArrayAdapter<>(getActivity(), R.layout.item, R.id.txtView_pop, listmenu);
                    listViewAdaptWidth.setAdapter(adapter);
                    listViewAdaptWidth.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            switch (i) {
                                case 0:
                                    //添加设备
                                    ToastUtil.show(getActivity(), "添加设备", 1);
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                                        cameraTask();
                                    } else {
                                        if (PermissionTool.isCameraCanUse()) {
                                            openCamera();
                                        } else {
                                            // 当前APP没有摄像头权限弹层，或者其他相关提示
                                            new AppSettingsDialog.Builder(getActivity(), getActivity().getResources().getString(R.string.camera_show))
                                                    .setTitle("权限申请")
                                                    .setPositiveButton("确认")
                                                    .setNegativeButton("取消", null /* click listener */)
                                                    .setRequestCode(REQUEST_CAMERA_PERM)
                                                    .build()
                                                    .show();
                                        }
                                    }
                                    break;
                                case 1:
                                    //添加场景
                                    ToastUtil.show(getActivity(), "添加场景", 1);
                                    Intent intent = new Intent(getActivity(), NewSceneAct.class);
                                    startActivity(intent);
                                    break;
                            }
                            popupWindow.dismiss();
                        }
                    });

                    popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

                }

                window = getActivity().getWindow();
                popupWindow.setBackgroundDrawable(new ColorDrawable());
                popupWindow.setOutsideTouchable(true);

                popupWindow.setFocusable(true);
                popupWindow.update();
                backgroundAlpha(0.5f);
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        backgroundAlpha(1.0f);
                    }
                });

                int[] position = new int[2];
                view.getLocationOnScreen(position);
                int y = position[1] + view.getMeasuredHeight();
                popupWindow.showAtLocation(add_img, Gravity.TOP | Gravity.RIGHT, 20, 150);

            }
        });

        getView().findViewById(R.id.msgcenter_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), MessageCenterActivity.class));
            }
        });

        getView().findViewById(R.id.set_wangguan_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (hasGateWay) {
                    //网关上电
                    //打开设置网关界面
                    String zigbee = zigbee_state_tv.getText().toString();
                    String wifi = wifistate_tv.getText().toString();

                    Intent intent = new Intent(getActivity(), GatewaySetActivity.class);
                    intent.putExtra("name", gatewayname);

                    intent.putExtra("zigbee", zigbee);
                    intent.putExtra("wifi", wifi);
                    startActivity(intent);
                } else {
                    addGateWay();
                }
            }
        });

        getView().findViewById(R.id.add_twobar_ll).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mDevice != null) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        cameraTask();
                    } else {
                        if (PermissionTool.isCameraCanUse()) {
                            openCamera();
                        } else {
                            // 当前APP没有摄像头权限弹层，或者其他相关提示
                            new AppSettingsDialog.Builder(getActivity(), getActivity().getResources().getString(R.string.camera_show))
                                    .setTitle("权限申请")
                                    .setPositiveButton("确认")
                                    .setNegativeButton("取消", null /* click listener */)
                                    .setRequestCode(REQUEST_CAMERA_PERM)
                                    .build()
                                    .show();
                        }
                    }
                } else {
                    //添加网关 不需要扫码
                    addGateWay();
                }
            }
        });

    }

    /**
     * 这里是添加网关的起点。。。。。。。。。。。。
     */
    public void addGateWay() {
        if (!checkNetwork(getActivity())) {
            Toast.makeText(getActivity(),
                    R.string.network_error, Toast.LENGTH_LONG).show();
            return;
        }
        Intent intent = new Intent(getActivity(), GosAirlinkChooseDeviceWorkWiFiActivity.class);
        startActivity(intent);
    }

    /**
     * 检查网络连通性（工具方法）
     *
     * @param context
     * @return
     */
    public boolean checkNetwork(Context context) {
        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo net = conn.getActiveNetworkInfo();
        if (net != null && net.isConnected()) {
            return true;
        }
        return false;
    }

    String code = "";

    private void initView() {
        if (mDevice != null || subList.size() > 0) {
        } else {
            showProgressDialog("加载中...");
        }

        listmenu = new ArrayList<>();
        listmenu.add("添加设备");
        listmenu.add("添加场景");
        initData();
        initUi();
        GosMessageHandler.getSingleInstance().StartLooperWifi(getActivity());

        uid = spf.getString("Uid", "");
        token = spf.getString("Token", "");

        deviceListadapter = new DeviceListAdapter();
        alarmSet = spf.getStringSet("alarmset", null);
        if (alarmSet == null) {
            alarmSet = new HashSet<>();
        }

        newSmoke = spf.getStringSet("newSmoke", null);
        oldSmoke= spf.getStringSet("oldSmoke", null);
        if (newSmoke == null) {
            newSmoke = new HashSet<>();
        }
        if (oldSmoke == null) {
            oldSmoke = new HashSet<>();
        }

        device_list.setAdapter(deviceListadapter);

        MsgCenter.addListener(new MsgListener() {
            @Override
            public void onMsg(Object sender, String msg, Object... args) {
                String mactv = ((String) args[0]).trim().replaceAll("\r|\n", "");
                spf.edit().putString("addMac", mactv.toUpperCase()).commit();
                if (stringIsMac(mactv)) {
                    if (!hasMac(mactv)) {
                        final List<String> macarray = new ArrayList<>();
                        macarray.add(mactv.toLowerCase());

                        new DialogUtil(getActivity(), true, true, "第一步\n长按设备的复位键或复位孔\n" +
                                "(漏水探测器请参照说明书设置)", "取消添加", "下一步", new DialogUtil.SureInterfance() {
                            @Override
                            public void sureTodo() {
                                //打开第二步提示
                                new DialogUtil(getActivity(), true, true, "第二步\n看到设备的指示灯闪烁后，点击下一步", "取消添加", "下一步", new DialogUtil.SureInterfance() {
                                    @Override
                                    public void sureTodo() {
                                        //打开第二步提示
                                        if (mDevice != null && mDevice.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceControlled) {
                                            deleteDev = false;
                                            mDevice.addSubDevice(macarray);
                                            mDevice.setListener(devmacListener);
                                            Log.i("addlogg", "mDevice.setListener===开始添加" + devmacListener.toString() + "....." + new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date(System.currentTimeMillis())));
                                            addTag = true;

                                            timer = new Timer();
                                            timer.schedule(new TimerTask() {
                                                int i = 70;

                                                @Override
                                                public void run() {
                                                    i--;
                                                    if (i == 0) {
                                                        Message message = new Message();
                                                        message.what = 102;
                                                        handler.sendMessage(message);
                                                    }
                                                }
                                            }, 0, 1000);
                                            Intent remind = new Intent(getActivity(), DoorAirlinkCountdownActivity.class);
                                            startActivity(remind);
                                        } else {
                                            App.getApp().showToast("休息一会，网关启动中...");
                                        }
                                    }

                                    @Override
                                    public void cancle() {

                                    }
                                }).showCustomDialog();
                            }

                            @Override
                            public void cancle() {

                            }
                        }).showCustomDialog();
                    } else {
                        App.getApp().showToast("您已添加了该设备");
                    }
                } else {
                    App.getApp().showToast("请扫描正确的设备ID");
                }
            }
        }, "mactv");
        MsgCenter.addListener(new MsgListener() {
            @Override
            public void onMsg(Object sender, String msg, Object... args) {
                String shareCode = (String) args[0];
                code = shareCode.substring(16, shareCode.length());
                GizDeviceSharing.setListener(shareListener);
                // 查看扫码邀请信息
                GizDeviceSharing.checkDeviceSharingInfoByQRCode(token, code);
            }
        }, "share");
        MsgCenter.addListener(new MsgListener() {
            @Override
            public void onMsg(Object sender, String msg, Object... args) {
                if (timer != null) {
                    timer.cancel();
                    timer = null;
                }
            }
        }, "cancle_timer");
        MsgCenter.addListener(new MsgListener() {
            @Override
            public void onMsg(Object sender, String msg, Object... args) {
                String macAddress = (String) args[0];
                if (alarmSet.contains(macAddress)) {
                    alarmSet.remove(macAddress);
                }
                spf.edit().putStringSet("alarmset", alarmSet).commit();
                deviceListadapter.setDeviceList(subList);
            }
        }, "update_alarm");
        MsgCenter.addListener(new MsgListener() {
            @Override
            public void onMsg(Object sender, String msg, Object... args) {
                String macAddress = (String) args[0];
                if (!alarmSet.contains(macAddress)) {
                    alarmSet.add(macAddress);
                }
                spf.edit().putStringSet("alarmset", alarmSet).commit();
                deviceListadapter.setDeviceList(subList);
            }
        }, "update_alarmset");
        MsgCenter.addListener(new MsgListener() {
            @Override
            public void onMsg(Object sender, String msg, Object... args) {
                mDevice.setListener(controlListener);
                mDevice.setSubscribe(MsgID.PS, true);
            }
        }, "getImei_again");
        onekey_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean chefang = spf.getBoolean("chefang", false);
                //                if (!chefang) {
                //                    spf.edit().putBoolean("chefang", true).commit();
                new DialogUtil(getActivity(), true, true, "在家模式：在此模式下，所有设备处于撤防状态，即被触发时有闪灯或鸣叫示警，但APP中的设备状态保持不变，信息推送和相关场景联动也处于关闭状态。", "取消", "好的", new DialogUtil.SureInterfance() {
                    @Override
                    public void sureTodo() {
                        //一键撤防
                        onekey(1);
                    }

                    @Override
                    public void cancle() {
                    }
                }).showCustomDialog();
                //                }
                /*else {
                    //一键撤防
                    onekey(1);
                }*/
            }
        });
        onekey_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean bufang = spf.getBoolean("bufang", false);
                //                if (!bufang) {
                //                    spf.edit().putBoolean("bufang", true).commit();
                new DialogUtil(getActivity(), true, true, "离家模式:在此模式下，所有设备都处于布防状态，设备的消息提醒和场景联动都处于开启状态。", "取消", "好的", new DialogUtil.SureInterfance() {
                    @Override
                    public void sureTodo() {
                        //一键布防
                        onekey(0);
                    }

                    @Override
                    public void cancle() {
                    }
                }).showCustomDialog();
                //                }
                /*else {
                    //一键布防
                    onekey(0);
                }*/
            }
        });
    }

    public void onekey(final int value) {
        RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
        Call<FeedBack> call = service.disarmAllSwitch(device_macs, value);
        call.enqueue(new Callback<FeedBack>() {
            @Override
            public void onResponse(Call<FeedBack> call, Response<FeedBack> response) {
                if (response != null && response.body() != null) {
                    int code = response.body().getCode();
                    if (code == 4) {
                        getDisarmSwitch();
                        if (value == 1) {
                            spf.edit().putString("onekey", "close").commit();
                            onekey_open.setBackgroundResource(R.drawable.oval_shape_unselected);
                            onekey_open.setTextColor(getResources().getColor(R.color.text_gray_light));
                            onekey_close.setBackgroundResource(R.drawable.oval_shape_selected);
                            onekey_close.setTextColor(getResources().getColor(R.color.title_common_color));
                        } else {
                            spf.edit().putString("onekey", "open").commit();
                            onekey_close.setBackgroundResource(R.drawable.oval_shape_unselected);
                            onekey_close.setTextColor(getResources().getColor(R.color.text_gray_light));
                            onekey_open.setBackgroundResource(R.drawable.oval_shape_selected);
                            onekey_open.setTextColor(getResources().getColor(R.color.title_common_color));
                        }
                    } else {
                        getDisarmSwitch();
                        App.getApp().showToast("设置失败，请重试");
                    }
                }
            }

            @Override
            public void onFailure(Call<FeedBack> call, Throwable t) {

            }
        });
    }

    public void initUi() {
        add_img = (ImageView) getView().findViewById(R.id.add_img);
        gateway_img = (ImageView) getView().findViewById(R.id.gateway_img);
        msgcenter_img = (ImageView) getView().findViewById(R.id.msgcenter_img);
        add_twobar_ll = (LinearLayout) getView().findViewById(R.id.add_twobar_ll);
        onekey_switch = (LinearLayout) getView().findViewById(R.id.onekey_switch);
        gateway_property_ll = (LinearLayout) getView().findViewById(R.id.gateway_property_ll);
        add_gateway_text = (TextView) getView().findViewById(R.id.add_gateway_text);
        add_device_text = (TextView) getView().findViewById(R.id.add_device_text);
        battery_tv = (TextView) getView().findViewById(R.id.battery_tv);
        zigbee_state_tv = (TextView) getView().findViewById(R.id.zigbee_state_tv);
        wifistate_tv = (TextView) getView().findViewById(R.id.wifistate_tv);
        device_list = (ListView) getView().findViewById(R.id.device_list);
        onekey_open = (TextView) getView().findViewById(R.id.onekey_open);
        onekey_close = (TextView) getView().findViewById(R.id.onekey_close);
    }

    GizDeviceSharingListener shareListener = new GizDeviceSharingListener() {
        @Override
        public void didCheckDeviceSharingInfoByQRCode(GizWifiErrorCode result, String userName,
                                                      final String productName, String deviceAlias, String expiredAt) {
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                // 成功
                String content = userName + "给你分享了\n" + productName;
                new DialogUtil(getActivity(), true, true, content, "拒绝", "接受", new DialogUtil.SureInterfance() {
                    @Override
                    public void sureTodo() {
                        if (productName.equals("中航网关") && mDevice != null) {
                            App.getApp().showToast("您已经添加了网关，不能继续添加网关了");
                        } else {
                            GizDeviceSharing.setListener(acceptListener);
                            // 接受二维码分享邀请
                            GizDeviceSharing.acceptDeviceSharingByQRCode(token, code);
                        }
                    }

                    @Override
                    public void cancle() {

                    }
                }).showCustomDialog();
            } else {

            }
        }
    };
    GizDeviceSharingListener acceptListener = new GizDeviceSharingListener() {
        @Override
        public void didAcceptDeviceSharingByQRCode(GizWifiErrorCode result) {
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                // 成功
                App.getApp().showToast("接受设备分享成功");
            } else {
                // 失败
                App.getApp().showToast("接受设备分享失败");
            }
        }
    };

    private void initData() {
        spf = getActivity().getSharedPreferences(SPF_Name, Context.MODE_PRIVATE);
        uid = spf.getString("Uid", "");
        token = spf.getString("Token", "");
    }

    /**
     * 请求CAMERA权限码
     */
    public static final int REQUEST_CAMERA_PERM = 101;

    /**
     * EsayPermissions接管权限处理逻辑
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @AfterPermissionGranted(REQUEST_CAMERA_PERM)
    public void cameraTask() {
        if (EasyPermissions.hasPermissions(getActivity(), Manifest.permission.CAMERA)) {
            // Have permission, do the thing!
            //            openCamera();
            if (PermissionTool.isCameraCanUse()) {
                openCamera();
            } else {
                // 当前APP没有摄像头权限弹层，或者其他相关提示
                new AppSettingsDialog.Builder(getActivity(), getActivity().getResources().getString(R.string.camera_show))
                        .setTitle("权限申请")
                        .setPositiveButton("确认")
                        .setNegativeButton("取消", null /* click listener */)
                        .setRequestCode(REQUEST_CAMERA_PERM)
                        .build()
                        .show();
            }
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(this, "需要请求拍照权限",
                    REQUEST_CAMERA_PERM, Manifest.permission.CAMERA);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        //        Toast.makeText(getActivity(), "执行onPermissionsDenied()...", Toast.LENGTH_SHORT).show();
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, getActivity().getResources().getString(R.string.camera_show))
                    .setTitle("权限申请")
                    .setPositiveButton("确认")
                    .setNegativeButton("取消", null /* click listener */)
                    .setRequestCode(REQUEST_CAMERA_PERM)
                    .build()
                    .show();
        }
    }


    private void openCamera() {
        Intent intent = new Intent(getActivity().getApplication(), CaptureActivity.class);
        intent.putExtra("from", "devicelist");
        startActivityForResult(intent, REQUEST_CODE);
    }

    Timer timer;
    boolean addTag = false;
    String addedMac;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                String mactext = bundle.getString("mac", "").trim().replaceAll("\r|\n", "");
                addedMac = mactext.toUpperCase();
                spf.edit().putString("addMac", addedMac).commit();
                if (stringIsMac(mactext)) {
                    if (!hasMac(mactext)) {
                        final List<String> macarray = new ArrayList<>();
                        macarray.add(mactext.toLowerCase());

                        new DialogUtil(getActivity(), true, true, "第一步\n长按设备的复位键或复位孔\n" +
                                "(漏水探测器请参照说明书设置)", "取消添加", "下一步", new DialogUtil.SureInterfance() {
                            @Override
                            public void sureTodo() {
                                //打开第二步提示
                                new DialogUtil(getActivity(), true, true, "第二步\n看到设备的指示灯闪烁后，点击下一步", "取消添加", "下一步", new DialogUtil.SureInterfance() {
                                    @Override
                                    public void sureTodo() {
                                        //打开第二步提示
                                        if (mDevice != null && mDevice.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceControlled) {
                                            deleteDev = false;
                                            mDevice.setListener(devmacListener);
                                            mDevice.addSubDevice(macarray);
                                            Log.i("addlogg", "mDevice.setListener===1224" + devmacListener.toString() + "....." + new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date(System.currentTimeMillis())));
                                            addTag = true;

                                            timer = new Timer();
                                            timer.schedule(new TimerTask() {
                                                int i = 70;

                                                @Override
                                                public void run() {
                                                    i--;
                                                    if (i == 0) {
                                                        Message message = new Message();
                                                        message.what = 102;
                                                        handler.sendMessage(message);
                                                    }
                                                }
                                            }, 0, 1000);
                                            Intent remind = new Intent(getActivity(), DoorAirlinkCountdownActivity.class);
                                            startActivity(remind);
                                        } else {
                                            App.getApp().showToast("休息一会，网关启动中...");
                                        }
                                    }

                                    @Override
                                    public void cancle() {

                                    }
                                }).showCustomDialog();
                            }

                            @Override
                            public void cancle() {

                            }
                        }).showCustomDialog();
                    } else {
                        App.getApp().showToast("您已添加了该设备");
                    }
                } else {
                    App.getApp().showToast("请扫描正确的设备二维码");
                }
            }
        }
    }

    private boolean stringIsMac(String val) {
        String trueMacAddress = "([A-Fa-f0-9]{2}){8}";
        // 这是真正的MAV地址；正则表达式；
        if (val.matches(trueMacAddress)) {
            return true;
        } else {
            return false;
        }
    }

    private boolean hasMac(String val) {
        if (subList.size() > 0) {
            for (int i = 0; i < subList.size(); i++) {
                if (subList.get(i).getMacAddress().toString().equals(val)) {
                    return true;
                }
            }
        }
        return false;
    }

    Timer bindTimer = null;
    /**
     * 添加子设备的回调
     */
    GizWifiDeviceListener devmacListener = new
            GizWifiCentralControlDeviceListener() {
                @Override
                public void didUpdateSubDevices(GizWifiCentralControlDevice device, GizWifiErrorCode result,
                                                List<GizWifiDevice> subDeviceList) {
                    if (deleteDev) {
                        if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                            GizWifiSDK.sharedInstance().setListener(mListener);
                            GizWifiSDK.sharedInstance().unbindDevice(uid, token, addedDevice.getDid());
                            isFromDeviceList = true;
                            Log.i("addlogg", "mDevice.setListener===分享失败后删除成功再解绑" + mListener.toString() + "....." + new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date(System.currentTimeMillis())));
                        }
                    } else {

                        Log.i("addlogg", "devicelist===devmaclistener的回调" + devmacListener.toString() + "....." + new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date(System.currentTimeMillis())));
                        addedDevice = null;
                        String addmac = spf.getString("addMac", "");
                        for (GizWifiDevice adddevice : subDeviceList) {
                            if (adddevice.getMacAddress().equals(addmac)) {
                                addedDevice = adddevice;
                                addDeviceSucdev = adddevice;
                            }
                        }
                        // 添加成功
                        if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS && subDeviceList != null && subDeviceList.size() > 0 && addedDevice != null) {
                            if (!addTag) {
                                return;
                            }
                            addTag = false;
                            if (addedDevice.isBind()) {
                                //绑定成功 分享
                                //强行分享 使其成为管理员、
                                // 设置设备分享监听
                                bindTimer = new Timer();
                                bindTimer.schedule(new TimerTask() {
                                    int i = 15;

                                    @Override
                                    public void run() {
                                        i--;
                                        if (i == 0) {
                                            Looper.prepare();
                                            Message message = new Message();
                                            message.what = 102;
                                            handler.sendMessage(message);
                                            Looper.loop();
                                        } else if (!TextUtils.isEmpty(addedDevice.getDid())) {
                                            Looper.prepare();
                                            GizDeviceSharing.setListener(setRoleListener);
                                            Log.i("addlogg", "devicelist===1300开始分享" + setRoleListener.toString() + "....." + new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date(System.currentTimeMillis())));
                                            // 在设备列表中找到可以分享的设备
                                            // 二维码分享设备
                                            GizDeviceSharing.sharingDevice(token, addedDevice.getDid(), GizDeviceSharingWay.GizDeviceSharingByQRCode, null, null);
                                            Looper.loop();
                                        }
                                    }
                                }, 0, 1000);
                            } else {
                                //绑定
                                String type = addedDevice.getProductKey();
                                String ps = "";
                                if (type.equals(MsgID.PK_DOOR)) {
                                    ps = MsgID.PS_DOOR;
                                } else if (type.equals(MsgID.PK_WATER)) {
                                    ps = MsgID.PS_WATER;
                                } else if (type.equals(MsgID.PK_GAS)) {
                                    ps = MsgID.PS_GAS;
                                } else if (type.equals(MsgID.PK_SMOKE)) {
                                    ps = MsgID.PS_SMOKE;
                                } else if (type.equals(MsgID.PK_ALARM)) {
                                    ps = MsgID.PS_ALARM;
                                }
                                GizWifiSDK.sharedInstance().setListener(mListener);
                                GizWifiSDK.sharedInstance().bindRemoteDevice(uid, token, addedDevice.getMacAddress(), addedDevice.getProductKey(), ps);
                                Log.i("addlogg", "devicelist===获取到设备后开始绑定" + mListener.toString() + "....." + new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date(System.currentTimeMillis())));
                            }
                        } else if (result != GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                            Message message = new Message();
                            message.what = 102;
                            handler.sendMessage(message);
                            disMissDialog();
                        }
                    }
                }
            };

    boolean deleteDev;
    GizDeviceSharingListener setRoleListener = new GizDeviceSharingListener() {
        // 实现设备分享的回调
        @Override
        public void didSharingDevice(GizWifiErrorCode result, String deviceID, int sharingID, Bitmap QRCodeImage) {
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                //添加主动刷新子设备方法
                if (mDevice != null && mDevice.getNetStatus() == GizWifiDeviceNetStatus.GizDeviceControlled) {
                    mDevice.setListener(devmacListener);
                    mDevice.updateSubDevices();
                    Log.i("addlogg", "mDevice.setListener===分享成功" + devmacListener.toString() + "....." + new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date(System.currentTimeMillis())));
                }
                // 分享成功即可提示添加设备成功
                //设置设备的短信提醒打开
                //判断短信总开关的状态
                String msgswitch = spf.getString("msgSwitch", "");
                if (TextUtils.isEmpty(msgswitch) || msgswitch.equals("open")) {
                    setDeviceMsgopen(addedDevice);
                    //调用接口使该设备处于布防状态
                }
                setOpen(addedDevice);
                Message message = new Message();
                message.what = 101;
                handler.sendMessage(message);
            } else if (result == GizWifiErrorCode.GIZ_OPENAPI_ONLY_OWNER_CAN_SHARE) {
                deleteDev = true;
                isFromDeviceList = true;
                Message message = new Message();
                message.what = 105;
                handler.sendMessage(message);
            } else {
                // 分享失败
                //再解绑设备
                Message message = new Message();
                message.what = 102;
                handler.sendMessage(message);
            }
        }
    };

    public void setDeviceMsgopen(GizWifiDevice device) {
        RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
        Call<FeedBack> call = service.controlDeviceSwitch(device.getMacAddress(), 1);
        call.enqueue(new Callback<FeedBack>() {
            @Override
            public void onResponse(Call<FeedBack> call, Response<FeedBack> response) {

            }

            @Override
            public void onFailure(Call<FeedBack> call, Throwable t) {

            }
        });
    }

    public void setOpen(GizWifiDevice device) {
        RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
        Call<FeedBack> call = service.disarmAllSwitch(device.getMacAddress(), 0);
        if (call == null) {
            return;
        }
        call.enqueue(new Callback<FeedBack>() {
            @Override
            public void onResponse(Call<FeedBack> call, Response<FeedBack> response) {
                if (response != null && response.body() != null) {
                    int code = response.body().getCode();
                    if (code == 4) {
                    } else {
                    }
                }
            }

            @Override
            public void onFailure(Call<FeedBack> call, Throwable t) {

            }
        });
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {

        WindowManager.LayoutParams lp = window.getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        window.setAttributes(lp);
    }

    public class DeviceListAdapter extends BaseAdapter {
        List<GizWifiDevice> subList;

        public void setDeviceList(List<GizWifiDevice> msubList) {
            if (msubList != null) {
                subList = msubList;
                notifyDataSetChanged();
            }
        }

        @Override
        public int getCount() {
            return subList == null ? 0 : subList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }


        @Override
        public View getView(final int i, View convertView, ViewGroup viewGroup) {
            View view = null;
            view = LayoutInflater.from(getActivity()).inflate(R.layout.device_listitem_lay, viewGroup, false);
            TextView listdevice_name = (TextView) view.findViewById(R.id.listdevice_name);
            TextView device_status = (TextView) view.findViewById(R.id.device_status);
            ImageView device_img = (ImageView) view.findViewById(R.id.device_img);
            CheckBox device_opener = (CheckBox) view.findViewById(R.id.device_opener);

            if (!TextUtils.isEmpty(subList.get(i).getAlias())) {
                listdevice_name.setText(subList.get(i).getAlias());
            } else {
                listdevice_name.setText(subList.get(i).getProductName());
            }
            if (subList.get(i).getProductKey().equals(MsgID.PK_DOOR)) {
                device_img.setImageResource(R.mipmap.door_icon);
            } else if (subList.get(i).getProductKey().equals(MsgID.PK_GAS)) {
                device_img.setImageResource(R.mipmap.gas_icon);
            } else if (subList.get(i).getProductKey().equals(MsgID.PK_WATER)) {
                device_img.setImageResource(R.mipmap.water_icon);
            } else if (subList.get(i).getProductKey().equals(MsgID.PK_ALARM)) {
                device_img.setImageResource(R.mipmap.alarm_icon);
            } else if (subList.get(i).getProductKey().equals(MsgID.PK_SMOKE)) {
                //TODO 添加烟感版本号的区分
                //添加过滤 如果newoldSmoke
                if (!newSmoke.contains(subList.get(i).getMacAddress().toString())&&!oldSmoke.contains(subList.get(i).getMacAddress().toString())) {
                    subList.get(i).setListener(deviceListener);
                    subList.get(i).getDeviceStatus(null);
                }
                if (newSmoke.contains(subList.get(i).getMacAddress().toString())) {
                    //newoldSmoke里有就是新烟感
                    device_img.setImageResource(R.mipmap.smoke_icon_hm);
                } else {
                    device_img.setImageResource(R.mipmap.smoke_icon);
                }
            }
            if (deviceworkList != null && deviceworkList.size() > 0) {
                for (int j = 0; j < deviceworkList.size(); j++) {
                    if (subList.get(i).getMacAddress().equals(deviceworkList.get(j).getMac())) {
                        if (deviceworkList.get(j).getDisarmSwitch() == 0) {
                            device_opener.setChecked(true);
                        } else {
                            device_opener.setChecked(false);
                        }
                    }
                }
            }

            device_opener.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
                    if (isChecked) {
                        RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
                        Call<FeedBack> call = service.disarmAllSwitch(subList.get(i).getMacAddress(), 0);
                        call.enqueue(new Callback<FeedBack>() {
                            @Override
                            public void onResponse(Call<FeedBack> call, Response<FeedBack> response) {
                                if (response != null && response.body() != null) {
                                    int code = response.body().getCode();
                                    if (code == 4) {
                                        getDisarmSwitch();
                                    } else {
                                        getDisarmSwitch();
                                        App.getApp().showToast("布防失败，请重试");
                                    }
                                }
                            }

                            @Override
                            public void onFailure(Call<FeedBack> call, Throwable t) {

                            }
                        });
                    } else {
                        RetrofitService service = RetrofitHelper.getInstance(getActivity()).getServer();
                        Call<FeedBack> call = service.disarmAllSwitch(subList.get(i).getMacAddress(), 1);
                        call.enqueue(new Callback<FeedBack>() {
                            @Override
                            public void onResponse(Call<FeedBack> call, Response<FeedBack> response) {
                                if (response != null && response.body() != null) {
                                    int code = response.body().getCode();
                                    if (code == 4) {
                                        getDisarmSwitch();
                                    } else {
                                        getDisarmSwitch();
                                        App.getApp().showToast("撤防失败，请重试");
                                    }
                                }
                            }

                            @Override
                            public void onFailure(Call<FeedBack> call, Throwable t) {

                            }
                        });
                    }
                }
            });

            if (subList.get(i).getNetStatus() == GizWifiDeviceNetStatus.GizDeviceOnline || subList.get(i).getNetStatus() == GizWifiDeviceNetStatus.GizDeviceControlled) {
                device_status.setText("正常" /*+ subList.get(i).getMacAddress().substring(12)*/);
                device_status.setTextColor(getResources().getColor(R.color.title_common_color));
            } else if (subList.get(i).getNetStatus() == GizDeviceOffline) {
                device_status.setText("掉线" /*+ subList.get(i).getMacAddress().substring(12)*/);
                device_status.setTextColor(getResources().getColor(R.color.red));
            }

            if (alarmSet != null && alarmSet.size() > 0) {
                if (alarmSet.contains(subList.get(i).getMacAddress())) {
                    device_status.setText("异常报警" /*+ subList.get(i).getMacAddress().substring(12)*/);
                    device_status.setTextColor(getResources().getColor(R.color.red));
                }
            }
            disMissDialog();
            return view;
        }
    }

    /**
     * 获取上报的设备信息
     */
    public GizWifiDeviceListener deviceListener = new GizWifiDeviceListener() {
        @Override
        public void didReceiveData(GizWifiErrorCode result, GizWifiDevice device, ConcurrentHashMap<String, Object> dataMap, int sn) {
            super.didReceiveData(result, device, dataMap, sn);
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                if (dataMap.get("data") != null) {
                    ConcurrentHashMap<String, Object> map = (ConcurrentHashMap<String, Object>) dataMap.get("data");
                    if (map != null) {

                        //门磁打开
                        if (device.getProductKey().equals(MsgID.PK_DOOR)) {
                            if (map.get("DoorState") != null) {

                                Boolean doorState = (Boolean) map.get("DoorState");
                                if (doorState != null && !doorState) {
                                    alarmSet.add(device.getMacAddress());
                                } else {
                                    if (alarmSet.contains(device.getMacAddress())) {
                                        alarmSet.remove(device.getMacAddress());
                                    }
                                }
                            }
                        }

                        if (device.getProductKey().equals(MsgID.PK_WATER)) {
                            //水浸报警
                            if (map.get("WaterLine") != null) {

                                int waterLine = (int) map.get("WaterLine");
                                if (0 != waterLine) {
                                    alarmSet.add(device.getMacAddress());
                                } else {
                                    if (alarmSet.contains(device.getMacAddress())) {
                                        alarmSet.remove(device.getMacAddress());
                                    }
                                }
                            }
                        }

                        //可燃气报警
                        if (device.getProductKey().equals(MsgID.PK_GAS)) {
                            if (map.get("AlarmStatus") != null) {
                                Boolean gasState = (Boolean) map.get("AlarmStatus");
                                if (gasState != null && gasState) {
                                    alarmSet.add(device.getMacAddress());
                                } else {
                                    if (alarmSet.contains(device.getMacAddress())) {
                                        alarmSet.remove(device.getMacAddress());
                                    }
                                }
                            }
                        }

                        //声光报警器
                        if (device.getProductKey().equals(MsgID.PK_ALARM)) {
                            if (map.get("AlarmStatus") != null) {
                                int gasState = (int) map.get("AlarmStatus");
                                if (gasState == 0 || gasState == 1 || gasState == 2 || gasState == 3) {
                                    alarmSet.add(device.getMacAddress());
                                } else {
                                    if (alarmSet.contains(device.getMacAddress())) {
                                        alarmSet.remove(device.getMacAddress());
                                    }
                                }
                            }
                        }

                        //烟雾报警
                        if (device.getProductKey().equals(MsgID.PK_SMOKE)) {
                            if (map.get("SoftWareVersion") != null) {
                                byte[] hard = (byte[]) map.get("SoftWareVersion");
                                String hardVi = new String(hard);
                                if (hardVi.contains("2")) {
                                    //TODO
                                    //新烟感时
                                    newSmoke.add(device.getMacAddress().toString());
                                } else {
                                    //旧烟感时
                                    oldSmoke.add(device.getMacAddress().toString());
                                }
                            }
                            if (map.get("SmokeAlarm") != null) {
                                Boolean alarmState = (Boolean) map.get("SmokeAlarm");
                                if (alarmState != null && alarmState) {
                                    alarmSet.add(device.getMacAddress());
                                } else {
                                    if (alarmSet.contains(device.getMacAddress())) {
                                        alarmSet.remove(device.getMacAddress());
                                    }
                                }
                            }
                        }
                        //TODO
                        spf.edit().putStringSet("newSmoke",newSmoke).commit();
                        spf.edit().putStringSet("oldSmoke",oldSmoke).commit();
                        spf.edit().putStringSet("alarmset", alarmSet).commit();
                        deviceListadapter.setDeviceList(subList);
                    }
                }
            }
        }
    };
    final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();

    // 将16进制的byte转为string，比如byte值为{0x62,0x63}，那么将转为“6263”
    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 3];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 3] = hexArray[v >>> 4];
            hexChars[j * 3 + 1] = hexArray[v & 0x0F];
            hexChars[j * 3 + 2] = ' ';
        }
        return new String(hexChars);
    }
}
